<?php

namespace SixShop\Lakala;

use SixShop\Lakala\Extension;
use SixShop\Lakala\OpenAPISDK\V2\V2Configuration;
use SixShop\Lakala\OpenAPISDK\V3\Configuration;
use SixShop\System\Trait\ConfigTrait;

/**
 * @property string $merchant_no 商户ID
 * @property string $term_no 终端号
 * @property string $notify_url 商户通知地址
 * @property string $complete_notify_url 收货确认通知地址
 * @property string $environment 环境
 * @property string $org_code 机构代码
 * @property string $sub_appid 子商户公众账号ID
 * @property string $receiver_agreement_file 默认合作协议文件
 * @property string $random_discount_max 随机立减金额上限
 * @property array{merchant_no:string,term_no:string}[] $sub_merchant_list 子商户列表
 * @property float $profit_share_fee 分账手续费百分比
 * @property int $profit_share_min 分账最低金额
 * @property int $profit_share_max 分账最高金额
 */
class Config
{
    use ConfigTrait {
        getConfig as traitGetConfig;
    }

    public function getConfig(string $key = null, mixed $default = null): mixed
    {
        if ($key == 'merchant_no') {
            return $this->getConfig('sub_merchant_list')[0]['merchant_no'];
        }
        if ($key == 'term_no') {
            return $this->getConfig('sub_merchant_list')[0]['term_no'];
        }
        return $this->traitGetConfig($key, $default);
    }

    public function getExtensionID(): string
    {
        return Extension::EXTENSION_ID;
    }

    protected function getOptions(): array
    {
        return [
            'gateway' => [
                'product' => 'https://s2.lakala.com', // 生产网关地址
                'test' => 'https://test.wsmsd.cn/sit',
            ],
        ];
    }

    /**
     * 获取V3配置
     * @return Configuration
     */
    public function getV3Config(): Configuration
    {
        return new Configuration($this->getCommonConfig());
    }

    /**
     * 获取V2配置
     * @return V2Configuration
     */
    public function getV2Config(): V2Configuration
    {
        return new V2Configuration($this->getCommonConfig());
    }

    private function getCommonConfig(): array
    {
        $signCert = $this->getConfig('sign_cert');
        $verifyCert = $this->getConfig('verify_cert');
        $gateway = $this->getConfig('gateway');

        // 校验必要字段
        if (!is_array($signCert) || !isset($signCert[0])) {
            throw new \InvalidArgumentException("sign_cert must be an array and contain at least one element.");
        }

        if (!is_array($verifyCert) || !isset($verifyCert[0])) {
            throw new \InvalidArgumentException("verify_cert must be an array and contain at least one element.");
        }

        if (!is_array($gateway) || !isset($gateway['test'], $gateway['product'])) {
            throw new \InvalidArgumentException("gateway config must contain both 'test' and 'product' keys.");
        }

        $environment = $this->getConfig('environment');

        return [
            'app_id' => $this->getConfig('appid'),
            'serial_no' => $this->getConfig('serial_no'),
            'sm4_key' => null,
            'merchant_private_key_path' => $this->buildPath($signCert[0]),
            'lkl_certificate_path' => $this->buildPath($verifyCert[0]),
            'app_debug' => $environment === 'test',
            'host_test' => $gateway['test'],
            'host_pro' => $gateway['product'],
        ];
    }

    private function buildPath(string $relativePath): string
    {
        return rtrim(public_path(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . ltrim($relativePath, DIRECTORY_SEPARATOR);
    }
}